# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
import random
from .userAgent import USER_AGENT_LIST
import time
from selenium import webdriver
from scrapy.http import HtmlResponse
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
class IqiyispiderSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

    def process_request(self, request, spider):
        user_agent = random.choice(USER_AGENT_LIST)
        if user_agent:
            print('user-agent:', user_agent)
            request.headers.setdefault('User-Agent', user_agent)


class JavaScriptMiddleware(object):
    def __init__(self):
        self.browser = webdriver.Firefox(executable_path='D:\Tool\火狐浏览器\geckodriver.exe')
        super(JavaScriptMiddleware, self).__init__()

    def process_request(self, request, spider):
        if spider.name == 'iQiYiSpider':
            if "https://www.guanggao365.com/advertisement/details?" not in request.url:
                print("PhantomJS is starting...")
                self.browser.get(request.url)
                time.sleep(3)
                print("访问：{0}".format(request.url))
                # 请求已完成，所以不用再发送到下载器。用HtmlResponse 之后就不会发送到downlaoder,而是直接返回给spider
                return HtmlResponse(url=self.browser.current_url,
                                    body=self.browser.page_source,
                                    encoding="utf-8",
                                    request=request)
        elif spider.name == 'BaiDuSpider':
            print("PhantomJS is starting...")
            self.browser.get(request.url)
            time.sleep(3)
            print("访问：{0}".format(request.url))
            # 请求已完成，所以不用再发送到下载器。用HtmlResponse 之后就不会发送到downlaoder,而是直接返回给spider
            return HtmlResponse(url=self.browser.current_url,
                                body=self.browser.page_source,
                                encoding="utf-8",
                                request=request)

        elif spider.name == 'iFengSpider':
            print("PhantomJS is starting...")
            self.browser.get(request.url)
            time.sleep(3)
            print("访问：{0}".format(request.url))
            # 请求已完成，所以不用再发送到下载器。用HtmlResponse 之后就不会发送到downlaoder,而是直接返回给spider
            return HtmlResponse(url=self.browser.current_url,
                                body=self.browser.page_source,
                                encoding="utf-8",
                                request=request)

        elif spider.name == 'car_image':
            print("PhantomJS is starting...")
            self.browser.get(request.url)
            time.sleep(3)
            print("访问：{0}".format(request.url))
            # 请求已完成，所以不用再发送到下载器。用HtmlResponse 之后就不会发送到downlaoder,而是直接返回给spider
            return HtmlResponse(url=self.browser.current_url,
                                body=self.browser.page_source,
                                encoding="utf-8",
                                request=request)

class LoginMiddle(object):
    def __init__(self):
        self.browser = webdriver.Firefox(executable_path='D:\Tool\火狐浏览器\geckodriver.exe')
        self.cookies = ''
        super(LoginMiddle, self).__init__()

    def process_request(self, request, spider):
        self.browser.get('https://www.guanggao365.com/login')
        time.sleep(1)
        username = self.browser.find_element_by_id('username1')
        password = self.browser.find_element_by_id('password1')
        username.send_keys('')
        password.send_keys('')
        time.sleep(3)
        self.browser.find_element_by_xpath('//button[@class="loginBtn"]').click()
        time.sleep(3)
        self.cookies = self.browser.get_cookies()
        return HtmlResponse(url=self.browser.current_url,
                            body=self.browser.page_source,
                            encoding='utf-8',
                            request=request)

class ProxyMiddleWare(object):
    """docstring for ProxyMiddleWare"""
    def process_request(self,request, spider):
        '''对request对象加上proxy'''
        proxy = self.get_random_proxy()
        print("this is request ip:"+proxy)
        request.meta['proxy'] = proxy


    def process_response(self, request, response, spider):
        '''对返回的response处理'''
        # 如果返回的response状态不是200，重新生成当前request对象
        if response.status != 200:
            proxy = self.get_random_proxy()
            print("this is response ip:"+proxy)
            # 对当前reque加上代理
            request.meta['proxy'] = proxy
            return request
        return response

    def get_random_proxy(self):
        '''随机从文件中读取proxy'''
        while 1:
            with open('E:\\pycharmProject\\iQiYiSpider\\iQiYiSpider\\proxies.txt', 'r') as f:
                proxies = f.readlines()
            if proxies:
                break
            else:
                time.sleep(1)
        proxy = random.choice(proxies).strip()
        return proxy
